package com.jkl.comm.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import com.aliyun.oss.OSSClient;
import com.jkl.comm.config.OssConfig;
import com.jkl.service.param.inter.IParamKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.io.Files;

@Service
public class FileService {
	@Autowired
	private OSSClient ossClient;
	@Autowired
	private OssConfig ossConfig;

	@Autowired
	private IParamKeyService paramKeyService;
	@Value("${systemconfig.file.dir}")
	private String FILE_DIR;
	@Value("${systemconfig.file.url}")
	private String FILE_URL_PREFIX;

	public String fileUpload(MultipartFile file) {
		File fileDir = new File(FILE_DIR);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}
		String originalFileName = file.getOriginalFilename();
		String suffix = originalFileName.substring(originalFileName.indexOf("."), originalFileName.length());
		String newName = UUID.randomUUID().toString().replace("-", "") + suffix;
		String newFilePath = new StringBuilder(FILE_DIR).append(newName).toString();
		File newFile = new File(newFilePath);
		try {
			if (paramKeyService.selectByStoreType().getKeyValue().equals("nas")){
				Files.write(file.getBytes(), newFile);
			}else if (paramKeyService.selectByStoreType().getKeyValue().equals("oss")){
				OssFileUpload(file,newFilePath);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return FILE_URL_PREFIX + newName;
	}

	private void OssFileUpload(MultipartFile file, String newFilePath){
		try {
			ossClient.putObject(ossConfig.getBucketName(),newFilePath,new ByteArrayInputStream(file.getBytes()));
			System.out.println("====");
		}catch (IOException e){
			e.printStackTrace();
		}

	}
}
